<template>
    <div>
        <el-button @click="start" type="primary" class="margin-right10">刷新</el-button>
        <!-- 学员选择器 -->
        <el-select v-model="selectedUser" placeholder="选择学员" :disabled="isStudentView"
            class="user-selector margin-right10" @change="handleUserChange">
            <el-option v-for="user in activityusersummarize" :key="user.userid" :label="user.username"
                :value="user.userid" />
        </el-select>
        <AIWarningTips :show="true" />
        <!-- Markdown 内容展示 -->
        <div class="markdown-container">
            <div class="markdown-content markdown-body" v-if="currentContent" v-html="renderMarkdown(currentContent)">
            </div>
            <div v-else class="no-data">暂无分析数据</div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import "github-markdown-css/github-markdown-light.css"; // 只引入亮色主题
import MarkdownIt from 'markdown-it';
import mermaid from 'mermaid';
import { computed, nextTick, onMounted, ref } from 'vue';
import { useStore } from 'vuex';
import { asyncGetactivityusersummarize } from '../../api';
import { Storekey } from '../../interface';
import Studycodemodel from '../../mysql_interface/studycodemodel';
import AIWarningTips from '../AIWarningTips.vue';

const p = defineProps<{ data: Studycodemodel.Iactivity, userId?: number }>();

const store = useStore(Storekey);
const user = computed(() => {
    return store.state.user;
});

const activityusersummarize = ref<any[]>([]);
const selectedUser = ref<number | undefined>(undefined);
const currentContent = ref<string>('');

const users = computed(() => {
    const t1 = p.data.activityuser?.map(c => c.user) || [];
    const t2 = p.data.team?.user ? [p.data.team.user] : [];
    const t3 = p.data.team?.teamuser?.map(c => c.user) || [];
    return [...new Set([...t1, ...t2, ...t3].filter(Boolean))];
});
// 学生只能选择自己，老师除外
const isStudentView = computed(() => {
    return !!(p.userId && !user.value?.isAdmin);
});

onMounted(() => { start(); });

async function start() {
    await getactivityusersummarize();
    handleUserChange(p.userId);
}

async function getactivityusersummarize() {
    try {
        activityusersummarize.value = await asyncGetactivityusersummarize({ activityid: p.data.ID });
        // 默认选择第一个学员
        if (activityusersummarize.value.length > 0) {
            selectedUser.value = activityusersummarize.value[0].userid;
            currentContent.value = activityusersummarize.value[0].content;
        }
    } catch (error) {
        console.error(error);
        // ElMessage.error(error || '获取数据失败');
    }
}

function handleUserChange(userid?: number) {
    if (!userid) return;
    selectedUser.value = userid;
    const selected = activityusersummarize.value.find(u => u.userid === userid);
    currentContent.value = selected?.content || '';
}

// Markdown 解析器
const md = new MarkdownIt({
    breaks: true, // 允许换行
    html: true,   // 允许 HTML
    linkify: true // 自动识别链接
});

// 解析 Markdown 并处理 Mermaid 代码块
function renderMarkdown(content: string) {
    if (!content) return "";
    let html = md.render(content);

    // 替换 Mermaid 代码块
    html = html.replace(
        /<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,
        (_, code) => `<div class="mermaid">${code}</div>`
    );

    // 等待 DOM 更新后渲染 Mermaid
    nextTick(() => {
        mermaid.init(undefined, document.querySelectorAll(".mermaid"));
    });

    return html;
}
</script>

<style scoped>
.margin-right10 {
    margin-right: 10px;
}

.user-selector {
    width: 200px;
}

.markdown-container {
    margin-top: 10px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    /* border: 1px solid #ebeef5; */
    overflow: auto;
}

.no-data {
    color: #999;
    text-align: center;
    padding: 20px;
}

/* Markdown 样式 */
.markdown-container :deep(pre) {
    background: #2d2d2d;
    color: #f8f8f8;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
}

/* Markdown内容样式 - 确保内容不会溢出 */
.markdown-content {
    /* 长单词或URL换行 */
    overflow-wrap: break-word;
    /* 更积极的换行策略 */
    word-break: break-word;
}

/* Mermaid 图表居中 */
:deep(.mermaid) {
    text-align: center;
    margin: 20px;
}
</style>

<style>
/* Mermaid 图表居中 */
.mermaid {
    text-align: center;
    margin: 20px;
}
</style>
